package com.mguo.backend.common;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.mguo.backend.config.BaseConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * 类CommonUtil的实现描述：TODO 类实现描述
 *
 * @author sunyj 2022/4/28 12:01
 */
@Slf4j
public class CommonUtil {

    /**
     * 获取接口访问凭证
     *
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public  static  String getToken(String appid, String appsecret) {
        //凭证获取(GET)
        String access_token =  null ;
        try  {
            String tokenUrl =  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET" ;
            String requestUrl = tokenUrl.replace( "APPID" , appid).replace( "APPSECRET" , appsecret);
            // 发起GET请求获取凭证
            JSONObject jsonObject = doGet(requestUrl);
            log.error("获取token返回值:" + jsonObject.toString());
            if  ( null  != jsonObject) {
                access_token = jsonObject.getString( "access_token" );
            }
        }  catch  (Exception e) {
            // 获取token失败
            log.error( "获取token失败 " , e);
        }
        return  access_token;
    }


    /**
     * 调用微信JS接口的临时票据
     *
     * @param access_token 接口访问凭证
     * @return
     */
    public  static  String getJsApiTicket(String access_token) {
        String ticket =  null ;
        try  {
            String url =  "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi" ;
            String requestUrl = url.replace( "ACCESS_TOKEN" , access_token);
            // 发起GET请求获取凭证

            JSONObject jsonObject = doGet(requestUrl);
            log.error("获取JsApiTicket返回值:" + jsonObject.toString());
            if  ( null  != jsonObject) {
                ticket = jsonObject.getString( "ticket" );
            }
        }  catch  (JSONException e) {
            // 获取token失败
            log.error( "获取JsApiTicket失败 " , e);
        }
        return  ticket;
    }


    /**
     * 获取openId
     *
     * @param code 用户code
     * @return
     */
    public  static  String getOpenId(String code) {
        String openid =  null ;
        JSONObject jsonObject =null;
        try  {
            String url =  "https://api.weixin.qq.com/sns/oauth2/access_token?appid=appId&secret=appSecret&code=userCode&grant_type=authorization_code" ;
            String requestUrl = url.replace( "appId" , BaseConfig.APP_ID);
            requestUrl = requestUrl.replace("appSecret",BaseConfig.APP_SECRET);
            requestUrl = requestUrl.replace("userCode", code);
            log.error("获取openidUrl: " + requestUrl);
            // 发起GET请求获取凭证

            jsonObject = doGet(requestUrl);
            log.error("获取openid返回值:" + jsonObject.toString());
            if  ( null  != jsonObject) {
                openid = jsonObject.getString( "openid" );
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new MguoException("SC_MG01" , "获取用户openid失败");
        }
        if(StringUtils.isBlank(openid)){
            if(jsonObject != null &&  StringUtils.isNotBlank(jsonObject.getString("errmsg"))){
                throw new MguoException("SC_MG01" , "获取用户openid失败"  +  jsonObject.getString("errmsg"));
            }
            throw new MguoException("SC_MG01" , "获取用户openid失败" );
        }
        return  openid;
    }


    /**
     * get请求
     * @return
     */
    public static JSONObject doGet(String url) {
        try {
            HttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            //请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                //读取返回数据
                String strResult = EntityUtils.toString(response.getEntity());
                return  JSONObject.parseObject(strResult);
            }
        } catch (IOException e) {
            log.error("httpUtils doGet error",e);
            return null;
        }
        return null;
    }

}
